package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.StudentHealth;
import com.example.mapper.StudentHealthMapper;
import com.example.service.StudentHealthService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class StudentHealthServiceImpl extends ServiceImpl<StudentHealthMapper, StudentHealth> implements StudentHealthService {
    
    @Override
    public List<StudentHealth> getHealthRecords(Long studentId) {
        LambdaQueryWrapper<StudentHealth> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StudentHealth::getStudentId, studentId)
            .orderByDesc(StudentHealth::getRecordTime);
        return this.list(wrapper);
    }
    
    @Override
    public StudentHealth getLatestHealthRecord(Long studentId) {
        LambdaQueryWrapper<StudentHealth> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StudentHealth::getStudentId, studentId)
            .orderByDesc(StudentHealth::getRecordTime)
            .last("LIMIT 1");
        return this.getOne(wrapper);
    }
    
    @Override
    public boolean addHealthRecord(StudentHealth health) {
        // 计算BMI
        if (health.getHeight() != null && health.getWeight() != null) {
            double bmi = calculateBMI(health.getHeight(), health.getWeight());
            health.setBmi(bmi);
            health.setHealthStatus(getHealthAdvice(bmi));
        }
        
        // 设置记录时间
        health.setRecordTime(LocalDateTime.now());
        
        return this.save(health);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateHealthRecord(StudentHealth health) {
        // 如果更新了身高或体重，重新计算BMI
        if (health.getHeight() != null || health.getWeight() != null) {
            StudentHealth existingHealth = getById(health.getId());
            if (existingHealth != null) {
                double height = health.getHeight() != null ? health.getHeight() : existingHealth.getHeight();
                double weight = health.getWeight() != null ? health.getWeight() : existingHealth.getWeight();
                double bmi = calculateBMI(height, weight);
                health.setBmi(bmi);
                health.setHealthStatus(getHealthAdvice(bmi));
            }
        }
        
        return updateById(health);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateHealth(StudentHealth health) {
        return updateById(health);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean generateReport(Long studentId) {
        // 获取学生最新的健康记录
        LambdaQueryWrapper<StudentHealth> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StudentHealth::getStudentId, studentId)
            .orderByDesc(StudentHealth::getRecordTime)
            .last("LIMIT 1");
        StudentHealth health = getOne(wrapper);
        
        if (health != null) {
            // 生成健康报告
            String report = generateHealthReport(health);
            health.setHealthStatus(report);
            return updateById(health);
        }
        return false;
    }

    private String generateHealthReport(StudentHealth health) {
        StringBuilder report = new StringBuilder();
        report.append("健康报告\n");
        report.append("身高: ").append(health.getHeight()).append("cm\n");
        report.append("体重: ").append(health.getWeight()).append("kg\n");
        report.append("BMI指数: ").append(health.getBmi()).append("\n");
        report.append("健康状况: ").append(getHealthAdvice(health.getBmi())).append("\n");
        report.append("报告时间: ").append(LocalDateTime.now()).append("\n");
        return report.toString();
    }
    
    @Override
    public boolean deleteHealthRecord(Long id) {
        return this.removeById(id);
    }
    
    @Override
    public double calculateBMI(double height, double weight) {
        // BMI = 体重(kg) / (身高(m) * 身高(m))
        double heightInMeters = height / 100.0;
        return weight / (heightInMeters * heightInMeters);
    }
    
    @Override
    public String getHealthAdvice(double bmi) {
        if (bmi < 18.5) {
            return "体重过轻，建议增加营养摄入";
        } else if (bmi < 24) {
            return "体重正常，请保持健康饮食";
        } else if (bmi < 28) {
            return "体重超重，建议适当控制饮食";
        } else {
            return "体重肥胖，建议加强锻炼并控制饮食";
        }
    }
} 